package com.abl.core.common.ws;

import com.abl.core.common.ws.handler.ChannelInit;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;

/**
 * 初始化Netty服务
 */
@Slf4j
@Configuration
public class StartWebSocket implements ApplicationRunner {

    private final EventLoopGroup mainGroup = new NioEventLoopGroup();

    private final EventLoopGroup subGroup = new NioEventLoopGroup();

    private final ServerBootstrap serverBootstrap = new ServerBootstrap();

    @Value("${server.netty.port:0}")
    private int port;

    @Value("${server.netty.openWs:false}")
    private boolean openWs;

    @Resource
    private ChannelInit channelHandlerDefault;

    public void run(ApplicationArguments args) {
        if (openWs) {
            log.error("WebSocket正在启动中.......端口：{}", port);
            serverBootstrap
                    .group(mainGroup, subGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(channelHandlerDefault)
                    .childHandler(channelHandlerDefault)
                    .bind(port);
            log.error("WebSocket启动成功,端口：{}", port);
        }
    }

}
